//
//  AddProjectComplainViewController.m
//  OCPB
//
//  Created by Siroj Chongkolwanont on 7/25/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "AddProjectComplainViewController.h"
#import "Province.h"
#import "Aumphur.h"
#import "Tumbon.h"
#import "ProjectComplain.h"

@interface AddProjectComplainViewController ()

@end

@implementation AddProjectComplainViewController

@synthesize provincePicker;
@synthesize aumphurPicker;
@synthesize tumbolPicker;
@synthesize provinceText;
@synthesize aumphurText;
@synthesize tumbolText;
@synthesize projectName;
@synthesize addrName;
@synthesize postText;
@synthesize telText;
@synthesize mobileText;
@synthesize faxText;
@synthesize complainController;
@synthesize scrollView;



NSMutableArray *provinceArray;
NSMutableArray *aumphurArray;
NSMutableArray *tumbonArray;



Province* currentProvince;
Aumphur* currentAumphur;
Tumbon*  currentTumbon;
UITextField* currentTextView;



id jsonObjectFromUrlString(NSString *urlString);


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    // The number of sections in the UIPickerView
    return 1;
}

- (void)load_province
{
    provinceArray = [[NSMutableArray alloc] init];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(@"http://www.aitproject.com/demo/webservice/public/service/province");
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSArray *allDara = [publicTimeline valueForKey:item];
            
            for(NSDictionary *dara in allDara )
            {
                Province* province = [[Province alloc] init];
                province.prov_code = [dara valueForKey:@"Prov_code"];
                province.prov_thai = [dara valueForKey:@"Prov_nameT"];
                province.prov_eng = [dara valueForKey:@"prov_nameE"];
                
                [provinceArray addObject:province];
            }
            
        }
    }
    
    currentProvince = provinceArray[0];
}

- (void)load_aumphur:(Province*)province
{
    aumphurArray = [[NSMutableArray alloc] init];
    
    NSString *aumphur_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/aumphur?id=%@", province.prov_code];
    
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(aumphur_str);
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSArray *allData = [publicTimeline valueForKey:item];
            
            for(NSDictionary *data in allData )
            {
                Aumphur* aumphur = [[Aumphur alloc] init];
                aumphur.prov_code = [data valueForKey:@"prov_code"];
                aumphur.aump_code = [data valueForKey:@"aump_code"];
                aumphur.aump_name = [data valueForKey:@"aump_name"];
                
                [aumphurArray addObject:aumphur];
            }
            
        }
    }
    
    currentAumphur = aumphurArray[0];
    
}


- (void)doneTapped
{
    [currentTextView resignFirstResponder];
    
    if(currentTextView.tag == 1)
    {
        currentTextView.text = currentProvince.prov_thai;
    }
    else if (currentTextView.tag ==2)
    {
        currentTextView.text = currentAumphur.aump_name;
    }
    else if (currentTextView.tag == 3)
    {
        currentTextView.text = currentTumbon.tum_name;
    }
    
}



- (void)load_tumbon:(Aumphur*)aumphur
{
    tumbonArray = [[NSMutableArray alloc] init];
    
    NSString *tumbon_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/tumbon?id=%@&prov_code=%@", aumphur.aump_code,aumphur.prov_code];
    
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(tumbon_str);
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSArray *allData = [publicTimeline valueForKey:item];
            
            for(NSDictionary *data in allData )
            {
                Tumbon* tumbon = [[Tumbon alloc] init];
                tumbon.prov_code = [data valueForKey:@"PROV_CODE"];
                tumbon.tum_code = [data valueForKey:@"TUMB_CODE"];
                tumbon.aump_code = [data valueForKey:@"AUMP_CODE"];
                tumbon.tum_name = [data valueForKey:@"TUMB_NAME"];
                tumbon.zip_code = [data valueForKey:@"TUMB_ZIPCODE"];
                
                [tumbonArray addObject:tumbon];
            }
            
        }
    }
    
    currentTumbon = tumbonArray[0];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    // The number of rows in the UIPickerView
    //return [pickerData count];
    
    if(pickerView == provincePicker)
        
        return [provinceArray count];
    
    else if (pickerView == aumphurPicker)
        return [aumphurArray count];
    
    else if (pickerView == tumbolPicker)
        return [tumbonArray count];
    
    return  0;
}


- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    // The data for each row in the UIPickerView
    //return [pickerData objectAtIndex:row];
    
    if(pickerView == provincePicker)
    {
        return  ((Province*)provinceArray[row]).prov_thai;
        
    }
    
    else if(pickerView == aumphurPicker)
    {
        return ((Aumphur*)aumphurArray[row]).aump_name;
        
    }
    else if(pickerView == tumbolPicker)
    {
        
        return ((Tumbon*)tumbonArray[row]).tum_name;
    }
    
    return @"";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // whatever you want to happen when a row is selected.
    
    // here I am assuming you want to remove from the picker and add to the table on selection
    
    if(pickerView == provincePicker)
    {
        [self load_aumphur:provinceArray[row]];
        [self load_tumbon:aumphurArray[0]];
        
        [aumphurPicker reloadAllComponents];
        [tumbolPicker reloadAllComponents];
        
        currentProvince = provinceArray[row];
        
    }
    else if(pickerView == aumphurPicker)
    {
        [self load_tumbon:aumphurArray[row]];
        [tumbolPicker reloadAllComponents];
        
        currentAumphur = aumphurArray[row];
        
    }
    else if (pickerView == tumbolPicker)
    {
        currentTumbon = tumbonArray[row];
    }
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
    }
    return YES;
}




- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    
    if ([string length] == 0 && range.length > 0)
    {
        return YES;
    }
    
    if ((textField == postText) &&  [textField.text length] == 5) {
        [textField resignFirstResponder];
    }
    
    
    if ((textField == mobileText || textField == telText || textField == faxText) &&  [textField.text length] == 10) {
        [textField resignFirstResponder];
    }
    
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
    }
    
    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([string rangeOfCharacterFromSet:notDigits].location != NSNotFound && (textField== postText|| textField == telText|| textField== mobileText || postText == textField || textField == faxText) )
    {
        return NO;
    }
    
    return YES;
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField.tag == 1 )
        provincePicker.hidden = NO;
    else if (textField.tag ==2 )
        aumphurPicker.hidden = NO;
    else if (textField.tag ==3 )
        tumbolPicker.hidden = NO;
    
    currentTextView = textField;
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [currentTextView bounds];
    rc = [currentTextView convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
    
}

- (void)viewDidLoad
{
    
    [self load_province];
    [self load_aumphur:provinceArray[0]];
    [self load_tumbon:aumphurArray[0]];
    
    UIToolbar* accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    accessoryView.barStyle = UIBarStyleBlackTranslucent;
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped)];
    
    accessoryView.items = [NSArray arrayWithObjects:space,done, nil];
    
    provinceText.inputAccessoryView = accessoryView;
    aumphurText.inputAccessoryView = accessoryView;
    tumbolText.inputAccessoryView = accessoryView;
    
    provinceText.inputView = provincePicker;
    aumphurText.inputView = aumphurPicker;
    tumbolText.inputView = tumbolPicker;
    
    
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    UIButton *button1 = [[UIButton alloc] init];
    button1.frame= CGRectMake(0,0,43,32);
    [button1 setBackgroundImage:[UIImage imageNamed: @"icon_back"] forState:UIControlStateNormal];
    
    [button1 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    

}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)AddProjectClick:(id)sender {
    NSArray *objects;
    NSArray *keys;
    

   objects = [NSArray arrayWithObjects:projectName.text
                   , addrName.text
                   , currentTumbon.tum_code
                   , currentAumphur.aump_code
                   , currentProvince.prov_code
                   , postText.text
                   , telText.text
                   , mobileText.text
                   ,faxText.text
                   ,nil];
        keys = [NSArray arrayWithObjects:@"Person_Comp_Project_Name"
                ,@"Person_Comp_Project_Address"
                ,@"Tumbol_id"
                ,@"Amphur_id"
                ,@"Province_id"
                ,@"PostCode"
                ,@"Person_Comp_Project_tel"
                ,@"Person_Comp_Project_mobile"
                ,@"Person_Comp_Project_fax"
                ,nil];
        
    
    
    NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    
    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonRequest is %@", jsonRequest);
    
    NSURL *url;

    url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/person-complained-project"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    
    //if ([mode isEqualToString:@"edit"])
    //{
    //    [request setValue:authorizationData  forHTTPHeaderField:@"Authorization"];
    //}
    
    
    [request setHTTPBody: requestData];
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    
    
    if (connection) {
        //responseData = [[NSMutableData alloc] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSError *error = nil;
    //NSString *jsonResponse =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    NSString* error_code = [jsonObject valueForKey:@"error_code"];
    
    
    NSString *jsonRequest =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonResponse is %@", jsonRequest);
    NSInteger isSuccess = 0;
    
    if(error_code.intValue  == 0 && error_code != NULL)
    {
        isSuccess = 1;
    }
    
    if(isSuccess != 1)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"OCPB!"
                                                          message:[jsonObject valueForKey:@"message"]
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        
    }
    else
    {
            NSDictionary *data = [jsonObject valueForKey:@"data"];
            
            
            ProjectComplain* project = [[ProjectComplain alloc] init];
            project.project_id = [data valueForKey:@"Person_Comp_Project_id"];
            project.project_name = [data valueForKey:@"Person_Comp_Project_Name"];
            
            [complainController setProjectComplain:project];
            
            [self.navigationController popViewControllerAnimated:YES];

    }
}
@end
